import { Injectable, Logger } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { Project } from 'src/interface/project.interface'
import { IResponse } from 'src/interface/response.interface'
import { UserService } from '../user/user.service'

const logger = new Logger('project.service')

@Injectable()
export class ProjectService {
    private response: IResponse
    private pageSize: number = 8

    constructor(
        @InjectModel('PROJECT_MODEL') private readonly projectModel: Model<Project>,
        private readonly userService: UserService,
    ) { }

    async createProject(project: Project) {
        const createProject = new this.projectModel(project)
        try {
            const project = await createProject.save()
            this.userService.addUserProject(project._id, project.creatorId)
            this.response = {
                code: 0,
                msg: {
                    msg: '创建项目成功',
                    projectId: project._id
                }
            }
        } catch (error) {
            logger.warn('创建项目失败')
            this.response = {
                code: 6,
                msg: '创建项目失败'
            }
        } finally {
            return this.response
        }
    }

    async deleteProject(projectId: string) {
        try {
            await this.projectModel.findByIdAndDelete(projectId)
            this.response = { code: 0, msg: '项目删除成功' }
        } catch (error) {
            this.response = { code: 7, msg: '项目删除失败' }
        }
        return this.response
    }

    async alterProject(projectId: string, project: Project) {
        try {
            await this.projectModel.findByIdAndUpdate(projectId, project)
            this.response = { code: 0, msg: '项目修改成功' }
        } catch (error) {
            this.response = { code: 7, msg: '项目修改失败' }
        }
        return this.response
    }

    async findProjectById(projectId: string) {
        try {
            const project = await this.projectModel.findById(projectId)
            this.response = { code: 0, msg: project }
        } catch (error) {
            this.response = { code: 7, msg: '没有查询到项目' }
        }
        return this.response
    }

    async getProjectsByUser(userId: string, page?: number) {
        try {
            const identities = {}
            const user = await this.userService.findOneByUserId(userId)
            const projectIds = user.projects.map(v => {
                identities[v.projectId] = v.identity
                return v.projectId
            })
            const pageNums = Math.ceil(user.projects.length / this.pageSize)
            let projects = await this.projectModel.find({ _id: { $in: projectIds } })
                .skip(page ? (page - 1) * this.pageSize : 0).limit(this.pageSize)
            // 增加时间和身份
            projects = projects.map(v => {
                const date: Date = v._id.getTimestamp()
                v['date'] = date.toLocaleString()
                v['identity'] = identities[v._id]
                return v
            })
            // const projects = (await this.projectModel.find({})).map(v => {
            //     const date: Date = v._id.getTimestamp()
            //     console.log(date)
            //     v['date'] = date.toLocaleString()
            //     return v
            // })
            this.response = { code: 0, msg: { projects, pageNums, page } }
        } catch (error) {
            this.response = { code: 7, msg: '查询项目失败' }
        }
        return this.response
    }
}
